<?php
/**
 * 报量单控制器
 */

namespace app\school\controller;

use app\common\model\Dose;
use app\common\model\Meal;
use app\common\model\Menu;
use app\common\model\Order;
use app\common\validate\OrderValidate;
use app\school\exception\ApiServiceException;
use app\school\service\OrderService;
use hg\apidoc\annotation as Apidoc;
use think\facade\Config;
use think\response\Json;

/**
 * @Apidoc\Title("报量单")
 * @Apidoc\Group("index")
 */
class OrderController extends ApiBaseController {
	/**
	 * @Apidoc\Title("定量清单记录")
	 * @Apidoc\Desc("列表")
	 * @Apidoc\Method("GET")
	 * @Apidoc\Url("/school/order/index")
	 * @Apidoc\Returned("data",        type="int",                 desc="desc")
	 */
	public function index(OrderService $service): Json {
		try {
			$this->param['school_id'] = $this->uid;
			$data = $service->getList($this->param, $this->page, $this->limit);
			$result = [
				'order' => $data,
			];

			return api_success($result);
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * @Apidoc\Title("提交报量单")
	 * @Apidoc\Desc("提交报量单")
	 * @Apidoc\Method("POST")
	 * @Apidoc\Url("/school/order/add")
	 * @Apidoc\Param("content",          type="array",desc="提交内容",children={
	 *     @Apidoc\Param("week", type="string", desc="日期"),
	 *     @Apidoc\Param("tag", type="string", desc="小学初中 0 1"),
	 *       @Apidoc\Param("detail", type="array", desc="菜谱清单",children={
	 *       	@Apidoc\Param("time", type="string", desc="早餐/午餐/晚餐"),
	 *       	@Apidoc\Param("meal_name", type="string", desc="套餐名称"),
	 *        	@Apidoc\Param("meal", type="array", desc="套餐",children={
	 *        		@Apidoc\Param("menu_name", type="string", desc="菜谱名称"),
	 *        		@Apidoc\Param("menu", type="array", desc="菜谱",children={
	 *       	 		@Apidoc\Param("menu_id", type="string", desc="菜谱"),
	 *       	 	 	@Apidoc\Param("type_id", type="string", desc="商品"),
	 *       	 	 	@Apidoc\Param("spec_id", type="string", desc="规格"),
	 *        	 	 	@Apidoc\Param("brand_id", type="string", desc="单位"),
	 *        	 	  	@Apidoc\Param("num", type="string", desc="数量"),
	 *        	 	}),
	 *           }),
	 *          @Apidoc\Param("num", type="string", desc="用餐人数"),
	 *       }),
	 *       @Apidoc\Param("detail2", type="array", desc="菜谱清单",children={
	 *       	@Apidoc\Param("type_id", type="string", desc="早餐/午餐/晚餐"),
	 *       	@Apidoc\Param("brand_id", type="string", desc="套餐名称"),
	 *        	@Apidoc\Param("spec_id", type="string", desc="套餐名称"),
	 *          @Apidoc\Param("num", type="string", desc="用餐人数"),
	 *       }),
	 *    })
	 * @Apidoc\Returned("data",        type="int",                 desc="desc")
	 */
	public function add(OrderValidate $validate, OrderService $service): Json {
		$week = date('w');
		if ($week == 0) {
			$week = 7;
		}
		$config = Config::get('site.site');
		if ($week > $config['week']) {
			return api_error('已截止提交下周的报量单');
		}
		$start = date('Y-m-d', strtotime('next monday'));
		$end = date('Y-m-d ', strtotime($start . '+ 6 days'));
		$find = Dose::where('school_id', $this->uid)->where('week', 'between', [$start, $end])->findOrEmpty();
		if (!$find->isEmpty()) {
			return api_error('已提交过下周的报量单');
		}
		$this->param['school_id'] = $this->uid;
		$this->param['code'] = $this->uid . date('YmdHis') . rand(10000, 99999);
		$check = $validate->scene('api_add')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		$result = Order::create($this->param);
		$content = $this->param['content'];
		foreach ($content as $key => $value) {
			$detail = $value['detail'];
			if ($value['tag'] == 0) {
				// foreach ($value['detail'] as $dk => $dv) {
				// 	$menu_id = [];
				// 	foreach ($dv['meal'] as $mk => $mv) {
				// 		$menu_detail = [];
				// 		foreach ($mv['menu'] as $mmk => $mmv) {
				// 			$menu_detail[] = $mmv;
				// 		}
				// 		$menu = Menu::where('id', $mv['menu_id'])->find();
				// 		if ($menu['detail'] != $menu_detail) {
				// 			$menu_data = [
				// 				'name' => $mv['menu_name'],
				// 				'old_id' => $mv['menu_id'],
				// 				'tag' => 1,
				// 				'detail' => $menu_detail,
				// 			];
				// 			$menu = Menu::create($menu_data);
				// 			$menu_id[]['menu_id'] = $menu->id;
				// 		} else {
				// 			$menu_id[]['menu_id'] = $mv['menu_id'];
				// 		}

				// 	}
				// 	$meal = Meal::where('id', $dv['meal_id'])->find();
				// 	if ($meal['detail'] != $meal_id) {
				// 		$meal_data = [
				// 			'name' => $dv['meal_name'],
				// 			'old_id' => $dv['meal_id'],
				// 			'tag' => 1,
				// 			'detail' => $menu_id,
				// 		];
				// 		$meal = Meal::create($meal_data);
				// 		$detail[$dk]['meal_id'] = $meal->id;
				// 	} else {
				// 		$detail[$dk]['meal_id'] = $dv['meal_id'];
				// 	}

				// }
			} else {
				foreach ($value['detail'] as $dk => $dv) {
					$menu_id = [];
					foreach ($dv['meal'] as $mk => $mv) {
						$menu_detail = [];
						foreach ($mv['menu'] as $mmk => $mmv) {
							$menu_detail[] = $mmv;
						}
						$menu = Menu::where('id', $mv['menu_id'])->find();
						if ($menu['detail'] != $menu_detail) {
							$menu_data = [
								'name' => $mv['menu_name'],
								'old_id' => $mv['menu_id'],
								'tag' => 1,
								'cate'=>1,
								'detail' => $menu_detail,
							];
							$menu = Menu::create($menu_data);
							$menu_id[]['menu_id'] = $menu->id;
						} else {
							$menu_id[]['menu_id'] = $mv['menu_id'];
						}

					}
					//$meal = Meal::where('id', $dv['meal_id'])->find();
					//if ($meal['detail'] != $meal_id) {
					$meal_data = [
						'name' => $dv['meal_name'],
						'old_id' => 0,
						'tag' => 1,
						'cate'=>1,
						'detail' => $menu_id,
					];
					$meal = Meal::create($meal_data);
					$detail[$dk]['meal_id'] = $meal->id;
					// } else {
					// 	$detail[$dk]['meal_id'] = $dv['meal_id'];
					// }

				}
			}

			$dose_data = [
				'school_id' => $this->uid,
				'order_id' => $result->id,
				'week' => $value['week'],
				'tag' => $value['tag'],
				'detail' => $detail,
				'detail2' => $value['detail2'],
			];
			Dose::create($dose_data);
		}
		return $result ? api_success() : api_error();
	}

	/**
	 * 详情
	 * @param OrderValidate $validate
	 * @param OrderService $service
	 * @return Json
	 */
	public function info(OrderValidate $validate, OrderService $service): Json {
		$check = $validate->scene('api_info')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {

			$result = $service->getDataInfo($this->id);
			return api_success([
				'order' => $result,
			]);

		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * 修改
	 * @param OrderService $service
	 * @param OrderValidate $validate
	 * @return Json
	 */
	public function edit(OrderService $service, OrderValidate $validate): Json {
		$check = $validate->scene('api_edit')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {
			$service->updateData($this->id, $this->param);
			return api_success();
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

	/**
	 * 删除
	 * @param OrderService $service
	 * @param OrderValidate $validate
	 * @return Json
	 */
	public function del(OrderService $service, OrderValidate $validate): Json {
		$check = $validate->scene('api_del')->check($this->param);
		if (!$check) {
			return api_error($validate->getError());
		}

		try {
			$service->deleteData($this->id);
			return api_success();
		} catch (ApiServiceException $e) {
			return api_error($e->getMessage());
		}
	}

}
